#include "operations_management.h"
#include "ui_operations_management.h"
#include "api.h"
#include <QDebug>
#include <QMessageBox>
#include <QPushButton>
#include <QEventLoop>

operations_management::operations_management(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::operations_management)
    , currentPage(1)
    , pageSize(10)
    , totalPages(1)
    , currentSearchText("")
{
    ui->setupUi(this);
    
    setupTable();
    setupConnections();
    loadData();
}

operations_management::~operations_management()
{
    this->close();
    delete ui;
}



void operations_management::setupTable()
{
    ui->dataTable->setColumnCount(11);
    QStringList headers;
    headers << tr("票种ID") << tr("票种名称") << tr("出发地") << tr("到达地") << tr("价格") << tr("库存") << tr("状态") 
            << tr("出发时间") << tr("到达时间") << tr("列车编号") << tr("删除操作");
    ui->dataTable->setHorizontalHeaderLabels(headers);
    
    ui->dataTable->setColumnWidth(0, 80);
    ui->dataTable->setColumnWidth(1, 120);
    ui->dataTable->setColumnWidth(2, 100);
    ui->dataTable->setColumnWidth(3, 100);
    ui->dataTable->setColumnWidth(4, 80);
    ui->dataTable->setColumnWidth(5, 80);
    ui->dataTable->setColumnWidth(6, 80);
    ui->dataTable->setColumnWidth(7, 100);
    ui->dataTable->setColumnWidth(8, 100);
    ui->dataTable->setColumnWidth(9, 100);
    ui->dataTable->setColumnWidth(10, 100);
    
    // 设置表格可编辑
    ui->dataTable->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
    ui->dataTable->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui->dataTable->setSelectionMode(QAbstractItemView::SingleSelection);
}

void operations_management::loadData()
{
    clearTable();
    
    // 构建搜索参数
    QJsonObject searchParams = buildSearchParams();
    
    Api* api = Api::getInstance();
    
    // 统一使用搜索接口，支持复合查询条件
    api->searchTicketsWithParams(searchParams, [this](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (success) {
            qDebug()<<response;
            QJsonArray tickets = response["tickets"].toArray();
            int totalCount = response["totalCount"].toString().toInt();
            
            // 更新分页信息
            totalPages = (totalCount + pageSize - 1) / pageSize;
            updatePageInfo();
            
            // 填充表格数据
            fillTableData(tickets);
        } else {
            QMessageBox::critical(this, "错误", "加载数据失败: " + errorMsg);
        }
    });
}

QJsonObject operations_management::buildSearchParams()
{
    QJsonObject params;
    params["page"] = currentPage;
    params["pageSize"] = pageSize;
    
    // 获取当前选择的类型
    QString selectedType = ui->typeComboBox->currentText();
    currentSearchType = selectedType;
    // 添加搜索条件
    if (!currentSearchText.isEmpty()) {
        params["searchText"] = currentSearchText;
    }
    
    if (!currentSearchType.isEmpty()) {
        params["searchType"] = currentSearchType;
    }
    
    return params;
}

QString operations_management::getCurrentTicketType()
{
    QString selectedType = ui->typeComboBox->currentText();
    if (selectedType == "Train") {
        return "火车";
    } else if (selectedType == "Car") {
        return "汽车";
    } else if (selectedType == "Plane") {
        return "飞机";
    } else {
        return "火车"; // 默认类型
    }
}

QJsonObject operations_management::buildTicketParams(const QString& ticketType)
{
    QString type = ticketType.isEmpty() ? getCurrentTicketType() : ticketType;
    QString newTicketId = "T" + QString::number(QDateTime::currentSecsSinceEpoch()).right(3);
    
    QJsonObject params;
    params["ticket_id"] = newTicketId;
    params["ticket_name"] = tr("新票种");
    params["ticket_type"] = type; // 添加票种类型字段
    params["price"] = 100.0;
    params["stock"] = 100;
    params["status"] = tr("可用");
    params["departure_time"] = "00:00";
    params["arrival_time"] = "00:00";
    params["train_number"] = "NEW000";
    
    // 根据票种类型设置默认的出发地和到达地
    if (type == "火车") {
        params["departure_location"] = "北京";
        params["arrival_location"] = "上海";
    } else if (type == "汽车") {
        params["departure_location"] = "广州";
        params["arrival_location"] = "深圳";
    } else if (type == "飞机") {
        params["departure_location"] = "成都";
        params["arrival_location"] = "重庆";
    }
    
    return params;
}

void operations_management::loadPageData()
{
    // 直接调用loadData，避免重复代码
    loadData();
}

void operations_management::clearTable()
{
    ui->dataTable->setRowCount(0);
}

void operations_management::updatePageInfo()
{
    ui->pageLabel->setText(tr("第 %1 页，共 %2 页").arg(currentPage).arg(totalPages));
    
    ui->firstPageBtn->setEnabled(currentPage > 1);
    ui->prevPageBtn->setEnabled(currentPage > 1);
    ui->nextPageBtn->setEnabled(currentPage < totalPages);
    ui->lastPageBtn->setEnabled(currentPage < totalPages);
}

void operations_management::onSearchButtonClicked()
{
    currentSearchText = ui->searchEdit->text().trimmed();
    currentPage = 1;
    loadData();
}

void operations_management::onAddButtonClicked()
{
    // 获取当前选择的票种类型
    QString currentType = getCurrentTicketType();
    
    // 创建并显示自定义添加票种对话框
    AddTicketDialog dialog(currentType, this);
    
    if (dialog.exec() == QDialog::Accepted) {
        // 获取用户输入的票种参数
        QJsonObject params = dialog.getTicketParams();
        QString ticketId = dialog.getTicketId();
        
        Api* api = Api::getInstance();
        
        // 使用QEventLoop实现同步等待
        QEventLoop loop;
        bool success = false;
        QString errorMsg;
        QJsonObject response;
        
        api->addTicket(params, [&](bool result, const QJsonObject& resp, const QString& error, int statusCode) {
            success = result;
            errorMsg = error;
            response = resp;
            loop.quit();
        });
        loop.exec();
        
        if (success) {
            QMessageBox::information(this, tr("成功"), 
                                   tr("%1票种添加成功！\n票种ID：%2\n票种名称：%3\n出发地：%4\n到达地：%5")
                                   .arg(params["ticket_type"].toString())
                                   .arg(ticketId)
                                   .arg(params["ticket_name"].toString())
                                   .arg(params["departure_location"].toString())
                                   .arg(params["arrival_location"].toString()));
            refreshData();
        } else {
            QMessageBox::critical(this, tr("错误"), 
                                 tr("添加%1票种失败: %2")
                                 .arg(params["ticket_type"].toString())
                                 .arg(errorMsg));
        }
    }
}

void operations_management::onFirstPageClicked()
{
    if (currentPage > 1) {
        currentPage = 1;
        loadPageData();
        updatePageInfo();
    }
}

void operations_management::onPrevPageClicked()
{
    if (currentPage > 1) {
        currentPage--;
        loadPageData();
        updatePageInfo();
    }
}

void operations_management::onNextPageClicked()
{
    if (currentPage < totalPages) {
        currentPage++;
        loadPageData();
        updatePageInfo();
    }
}

void operations_management::onLastPageClicked()
{
    if (currentPage < totalPages) {
        currentPage = totalPages;
        loadPageData();
        updatePageInfo();
    }
}

void operations_management::onSaveAndRefreshClicked()
{
    if (saveDataToDatabase()) {
        refreshData();
        QMessageBox::information(this, tr("成功"), tr("数据保存并刷新成功！"));
    }
}

void operations_management::onTableItemDoubleClicked(int row, int column)
{
    // 直接进入编辑模式，不显示提示框
    ui->dataTable->editItem(ui->dataTable->item(row, column));
}

bool operations_management::saveDataToDatabase()
{
    Api* api = Api::getInstance();
    
    try {
        for (int row = 0; row < ui->dataTable->rowCount(); ++row) {
            QString ticketId = ui->dataTable->item(row, 0)->text();
            QString ticketName = ui->dataTable->item(row, 1)->text();
            QString departureLocation = ui->dataTable->item(row, 2)->text();
            QString arrivalLocation = ui->dataTable->item(row, 3)->text();
            double price = ui->dataTable->item(row, 4)->text().remove(QRegularExpression("[^0-9.]")).toDouble();
            int stock = ui->dataTable->item(row, 5)->text().remove(QRegularExpression("[^0-9]")).toInt();
            QString status = ui->dataTable->item(row, 6)->text();
            QString departureTime = ui->dataTable->item(row, 7)->text();
            QString arrivalTime = ui->dataTable->item(row, 8)->text();
            QString trainNumber = ui->dataTable->item(row, 9)->text();
            
            // 使用API更新数据
            QJsonObject params;
            params["ticket_id"] = ticketId;
            params["ticket_name"] = ticketName;
            params["departure_location"] = departureLocation;
            params["arrival_location"] = arrivalLocation;
            params["price"] = price;
            params["stock"] = stock;
            params["status"] = status;
            params["departure_time"] = departureTime;
            params["arrival_time"] = arrivalTime;
            params["train_number"] = trainNumber;
            
            // 同步调用API更新票种信息
            bool success = false;
            QString errorMsg;
            
            // 使用QEventLoop实现同步等待
            QEventLoop loop;
            api->updateTicket(params, [&](bool result, const QJsonObject& response, const QString& error, int statusCode) {
                success = result;
                errorMsg = error;
                loop.quit();
            });
            loop.exec();
            
            if (!success) {
                throw std::runtime_error(errorMsg.toStdString());
            }
        }
        
        return true;
    } catch (const std::exception& e) {
        QMessageBox::critical(this, tr("保存错误"), tr("保存数据时出错: ") + QString::fromUtf8(e.what()));
        return false;
    }
}

void operations_management::onCellChanged(int row, int column)
{
    // 如果是第0列（票种ID），不允许编辑
    if (column == 0) {
        QTableWidgetItem* item = ui->dataTable->item(row, column);
        if (item) {
            item->setFlags(item->flags() & ~Qt::ItemIsEditable);
        }
        return;
    }
    
    // 检查数据有效性
    QTableWidgetItem* item = ui->dataTable->item(row, column);
    if (!item) return;
    
    QString text = item->text();
    
    // 根据列类型进行数据验证
    switch (column) {
        case 4: // 价格列
        {
            bool ok;
            double price = text.toDouble(&ok);
            if (!ok || price < 0) {
                QMessageBox::warning(this, "输入错误", "价格必须是大于等于0的数字");
                item->setText("0.00");
                return;
            }
            break;
        }
        case 5: // 库存列
        {
            bool ok;
            int stock = text.toInt(&ok);
            if (!ok || stock < 0) {
                QMessageBox::warning(this, "输入错误", "库存必须是大于等于0的整数");
                item->setText("0");
                return;
            }
            break;
        }
        case 6: // 状态列
        {
            if (text != "可用" && text != "不可用") {
                QMessageBox::warning(this, "输入错误", "状态只能是'可用'或'不可用'");
                item->setText("可用");
                return;
            }
            break;
        }
    }
    
    // 使用API更新数据
    QString ticketId = ui->dataTable->item(row, 0)->text();
    QString ticketName = ui->dataTable->item(row, 1)->text();
    QString departureLocation = ui->dataTable->item(row, 2)->text();
    QString arrivalLocation = ui->dataTable->item(row, 3)->text();
    double price = ui->dataTable->item(row, 4)->text().remove(QRegularExpression("[^0-9.]")).toDouble();
    int stock = ui->dataTable->item(row, 5)->text().remove(QRegularExpression("[^0-9]")).toInt();
    QString status = ui->dataTable->item(row, 6)->text();
    QString departureTime = ui->dataTable->item(row, 7)->text();
    QString arrivalTime = ui->dataTable->item(row, 8)->text();
    QString trainNumber = ui->dataTable->item(row, 9)->text();
    
    Api* api = Api::getInstance();
    QJsonObject params;
    params["ticket_id"] = ticketId;
    params["ticket_name"] = ticketName;
    params["departure_location"] = departureLocation;
    params["arrival_location"] = arrivalLocation;
    params["price"] = price;
    params["stock"] = stock;
    params["status"] = status;
    params["departure_time"] = departureTime;
    params["arrival_time"] = arrivalTime;
    params["train_number"] = trainNumber;
    
    api->updateTicket(params, [this, row, column](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
        if (!success) {
            QMessageBox::critical(this, "更新失败", "更新票种信息失败: " + errorMsg);
            // 恢复原始数据
            loadData();
        }
    });
}

void operations_management::refreshData()
{
    currentPage = 1;
    currentSearchText.clear();
    currentSearchType.clear();
    ui->searchEdit->clear();
    ui->typeComboBox->setCurrentIndex(0);
    loadData();
}

void operations_management::onTypeComboBoxChanged()
{
    currentPage = 1;
    loadData();
}

void operations_management::fillTableData(const QJsonArray& tickets)
{
    // 先设置行数，再填充数据
    ui->dataTable->setRowCount(tickets.size());

    // qDebug()<<ui->dataTable->columnCount();
    // qDebug()<<ui->dataTable->rowCount();
    for (int i = 0; i < tickets.size(); ++i) {
        QJsonObject ticket = tickets[i].toObject();

        // 直接使用循环索引作为行号
        int row = i;

        QLabel *idItem = new QLabel(ticket["ticket_id"].toString());

        ui->dataTable->setCellWidget(row, 0, idItem);

        ui->dataTable->setCellWidget(row, 1, new QLabel(ticket["ticket_name"].toString()));
        ui->dataTable->setCellWidget(row, 2, new QLabel(ticket["departure_location"].toString()));
        ui->dataTable->setCellWidget(row, 3, new QLabel(ticket["arrival_location"].toString()));
        ui->dataTable->setCellWidget(row, 4, new QLabel(ticket["price"].toString()));
        ui->dataTable->setCellWidget(row, 5, new QLabel(ticket["stock"].toString()));
        ui->dataTable->setCellWidget(row, 6, new QLabel(ticket["status"].toString()));
        ui->dataTable->setCellWidget(row, 7, new QLabel(ticket["departure_time"].toString()));
        ui->dataTable->setCellWidget(row, 8, new QLabel(ticket["arrival_time"].toString()));
        ui->dataTable->setCellWidget(row, 9, new QLabel(ticket["train_number"].toString()));

        // 添加删除按钮
        QPushButton *deleteBtn = new QPushButton("删除");
        connect(deleteBtn, &QPushButton::clicked, this, [this, row]() {
            onDeleteButtonClicked();
        });
        ui->dataTable->setCellWidget(row, 10, deleteBtn);
    }
}
void operations_management::onDeleteButtonClicked()
{
    // 获取触发删除操作的按钮
    QPushButton *deleteBtn = qobject_cast<QPushButton*>(sender());
    if (!deleteBtn) {
        // 如果不是按钮触发的，尝试获取当前选中的行
        QModelIndexList selectedRows = ui->dataTable->selectionModel()->selectedRows();
        if (selectedRows.isEmpty()) {
            QMessageBox::warning(this, "警告", "请先选择要删除的票种！");
            return;
        }
    }
    
    int row;
    if (deleteBtn) {
        // 从按钮属性中获取行号
        row = deleteBtn->property("row").toInt();
    } else {
        // 从选择中获取行号
        row = ui->dataTable->selectionModel()->selectedRows().first().row();
    }
    
    QString ticketId = ui->dataTable->item(row, 0)->text();
    QString ticketName = ui->dataTable->item(row, 1)->text();
    QString ticketType = ui->dataTable->item(row, 2)->text();
    
    // 确认删除对话框，包含票种类型信息
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, 
        "确认删除", 
        QString("确定要删除%1票种 \"%2\" (ID: %3) 吗？\n\n删除后将无法恢复！")
            .arg(ticketType)
            .arg(ticketName)
            .arg(ticketId),
        QMessageBox::Yes | QMessageBox::No,
        QMessageBox::No
    );
    
    if (reply == QMessageBox::Yes) {
        Api* api = Api::getInstance();
        
        // 构建包含票种类型的删除参数
        QJsonObject deleteParams;
        deleteParams["ticket_type"] = ticketType;
        deleteParams["ticket_name"] = ticketName;
        
        // 使用新的带参数删除方法
        api->deleteTicketWithParams(ticketId, deleteParams, [this, ticketType, ticketName, ticketId](bool success, const QJsonObject& response, const QString& errorMsg, int statusCode) {
            if (success) {
                QMessageBox::information(this, "删除成功", 
                    QString("%1票种 \"%2\" (ID: %3) 已成功删除！")
                        .arg(ticketType)
                        .arg(ticketName)
                        .arg(ticketId));
                refreshData();
            } else {
                QMessageBox::critical(this, "删除失败", 
                    QString("删除%1票种失败：%2\n请检查网络连接或联系管理员。")
                        .arg(ticketType)
                        .arg(errorMsg));
            }
        });
    }
}

void operations_management::setupConnections()
{
    // 按钮连接
    connect(ui->addButton, &QPushButton::clicked, this, &operations_management::onAddButtonClicked);
    connect(ui->saveRefreshButton, &QPushButton::clicked, this, &operations_management::onSaveAndRefreshClicked);
    connect(ui->searchButton, &QPushButton::clicked, this, &operations_management::onSearchButtonClicked);
    
    // 分页按钮连接
    connect(ui->firstPageBtn, &QPushButton::clicked, this, &operations_management::onFirstPageClicked);
    connect(ui->prevPageBtn, &QPushButton::clicked, this, &operations_management::onPrevPageClicked);
    connect(ui->nextPageBtn, &QPushButton::clicked, this, &operations_management::onNextPageClicked);
    connect(ui->lastPageBtn, &QPushButton::clicked, this, &operations_management::onLastPageClicked);
    
    // 表格双击事件连接
    connect(ui->dataTable, &QTableWidget::cellDoubleClicked, this, &operations_management::onTableItemDoubleClicked);
    
    // 表格内容变化事件连接
    connect(ui->dataTable, &QTableWidget::cellChanged, this, &operations_management::onCellChanged);
    
    // 类型下拉框变化事件连接
    connect(ui->typeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &operations_management::onTypeComboBoxChanged);
}
